package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcLabReportService;
import com.dhcc.cdc.busi.service.ICdcLabSetService;
import com.dhcc.cdc.busi.service.ICdcLabVisitService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 检验报告表数据服务层接口
 * 
 * @ClassName: LabReportServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-04-26 16:21:41
 */
@Service("labReportService")
public class CdcLabReportServiceImpl extends BaseServiceImpl<CdcLabReportMapper, CdcLabReportEntity>
		implements ICdcLabReportService {
	@Autowired
	private ICdcLabVisitService labvisitSrv;
	@Autowired
	ICdcDictionaryService dictritionSrv;
	@Autowired
	ICdcDataService dataSrv;
	@Autowired
	ICdcLabSetService labsetSrv;

	@Autowired
	private CdcEpisodeMapper cdcEpisodeMapper;

	@Autowired
	private CdcLabVisitMapper cdcLabVisitMapper;

	@Autowired
	private CdcDictionaryMapper cdcDictionaryMapper;

	@Autowired
	private CdcDataMapper cdcDataMapper;

	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;

	@Autowired
	private CdcLabItemMapper cdcLabItemMapper;
	
	@Autowired
	private CdcLabResultMapper cdcLabResultMapper;
	
	@Autowired
    private CdcUserMapper cdcUserMapper;

	Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public List<CdcLabReportEntity> page(Page<CdcLabReportEntity> page, Map<String, Object> map) {
		return warpReport(this.baseMapper.page(page, map));
	}

	@Override
	public List<CdcLabReportEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	public List<CdcLabReportEntity> warpReport(List<CdcLabReportEntity> list) {
		Map<Long, Object> cacheDic = new HashMap<Long, Object>();
		for (CdcLabReportEntity report : list) {
			if (report.getLabVisitId() != null) {
				if (cacheDic.containsKey(report.getLabVisitId())) {
					report.setLabVisit((CdcLabVisitEntity) cacheDic.get(report.getLabVisitId()));
				} else {
					CdcLabVisitEntity labVisit = this.labvisitSrv.selectById(report.getLabVisitId());
					report.setLabVisit(labVisit);
					cacheDic.put(report.getLabVisitId(), labVisit);
				}

				CdcLabSetEntity labSet = null;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("labVisitId", report.getLabVisitId());
				List<CdcLabSetEntity> labSetList = this.labsetSrv.list(map);
				if (labSetList.size() > 0) {
					labSet = labSetList.get(0);
				} else {
					labSet = new CdcLabSetEntity();
				}
				report.setLabset(labSet);
			} else {
				report.setLabVisit(new CdcLabVisitEntity());
				report.setLabset(new CdcLabSetEntity());
			}
			if (report.getBusLabReportStatusId() != null) {
				if (cacheDic.containsKey(report.getBusLabReportStatusId())) {
					report.setBusLabReportStatus((CdcDictionaryEntity) cacheDic.get(report.getBusLabReportStatusId()));
				} else {
					CdcDictionaryEntity orderStatus = this.dictritionSrv.selectById(report.getBusLabReportStatusId());
					report.setBusLabReportStatus(orderStatus);
					cacheDic.put(report.getBusLabReportStatusId(), orderStatus);
				}
			} else {
				report.setBusLabReportStatus(new CdcDictionaryEntity());
			}
			if (report.getDataId() != null) {
				if (cacheDic.containsKey(report.getDataId())) {
					report.setData((CdcDataEntity) cacheDic.get(report.getDataId()));
				} else {
					CdcDataEntity data = this.dataSrv.selectById(report.getDataId());
					report.setData(data);
					cacheDic.put(report.getDataId(), data);
				}
			} else {
				report.setData(new CdcDataEntity());
			}
		}

		return list;
	}

	@Override
	public String handleXmlData(String dataStr) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			Iterator<Element> iter = rootElt.elementIterator("labreport"); // 获取根节点下的子节点labreport
			// 遍历labreport节点
			while (iter.hasNext()) {
				Element labrepEle = iter.next();
				String xcode = labrepEle.elementTextTrim("xcode"); // 索引码
				String episodeid = labrepEle.elementTextTrim("episodeid"); // 就诊记录
				String labvisitid = labrepEle.elementTextTrim("labvisitid"); // 标本送检记录
				String reportid = labrepEle.elementTextTrim("reportid"); // 报告ID
				String reportnum = labrepEle.elementTextTrim("reportnum"); // 序号
				String represult = labrepEle.elementTextTrim("result"); // 报告结果
				String buslabreportstatuscode = labrepEle.elementTextTrim("buslabreportstatuscode"); // 状态
				String buslabreportstatusdesc = labrepEle.elementTextTrim("buslabreportstatusdesc"); // 状态
				String reportdatestr = labrepEle.elementTextTrim("reportdate"); // 录入日期
				String reportusername = labrepEle.elementTextTrim("reportusername"); // 录入人
				String checkdatestr = labrepEle.elementTextTrim("checkdate"); // 审核日期
				String checkusername = labrepEle.elementTextTrim("checkusername"); // 审核人
				String updatetimestr = labrepEle.elementTextTrim("updatetime"); // 更新时间
				String updateuserid = labrepEle.elementTextTrim("updateuserid"); // 更新人
				String opercode = labrepEle.elementTextTrim("opercode"); // 操作码
				// 先保存报告 ---再保存检验结果
				CdcLabReportEntity labrep = new CdcLabReportEntity();
				labrep.setXcode(xcode);
				CdcDataEntity cdcDataEntity = new CdcDataEntity();
				cdcDataEntity.setCode("LabData");
				cdcDataEntity.setIsActive(1);
				cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
				Long dataId = cdcDataEntity.getId();
				//获取basedataId
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
				if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		labrep.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		labrep.setUpdateBy(updateuser);
            	}
				if ("1".equals(opercode)) {// 保存/修改
					// 获取episodeid
					CdcEpisodeEntity cdcEpisodeEntity = new CdcEpisodeEntity();
					cdcEpisodeEntity.setXcode(episodeid);
					cdcEpisodeEntity = cdcEpisodeMapper.selectOne(cdcEpisodeEntity);// 就诊信息没在库中？？？
					Long epsid = cdcEpisodeEntity.getId();
					labrep.setEpisodeId(epsid);
					// 获取检验样本表中的ID
					CdcLabVisitEntity cdcLabVisitEntity = new CdcLabVisitEntity();
					cdcLabVisitEntity.setXcode(labvisitid);
					cdcLabVisitEntity = cdcLabVisitMapper.selectOne(cdcLabVisitEntity);// 样本没在库中？？？
					Long labvisitlongid = cdcLabVisitEntity.getId();
					labrep.setLabVisitId(labvisitlongid);
					if (CommonUtil.isNotEmpty(reportid)) {
						labrep.setReportId(reportid);
					}
					if (CommonUtil.isNotEmpty(reportnum)) {
						labrep.setReportNum(reportnum);
					}
					if (CommonUtil.isNotEmpty(represult)) {
						labrep.setResult(represult);
					}
					// 获取ID
					if (CommonUtil.isNotEmpty(buslabreportstatuscode)) {
						CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
						cdcDictypeEntity.setCode("bus_lab_status");
						cdcDictypeEntity.setIsActive(1);
						cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
						Long diclabstatusId = cdcDictypeEntity.getId();
						// 如果没有对应ID就要插入
						CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
						cdcDictionaryEntity.setDictypeId(diclabstatusId);
						cdcDictionaryEntity.setCode(buslabreportstatuscode);
						cdcDictionaryEntity.setIsActive(1);
						cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
						// 判断字典存在不存在
						Long buslabstatusid = null;
						if (CommonUtil.isEmpty(cdcDictionaryEntity)) {// 不存在 保存到字典表里面
							cdcDictionaryEntity = new CdcDictionaryEntity();
							cdcDictionaryEntity.setDictypeId(diclabstatusId);
							cdcDictionaryEntity.setCode(buslabreportstatuscode);
							cdcDictionaryEntity.setDescription(buslabreportstatusdesc);
							cdcDictionaryEntity.setIsActive(1);
							// 保存字典
							cdcDictionaryMapper.insert(cdcDictionaryEntity);
							buslabstatusid = cdcDictionaryEntity.getId();
						} else {
							buslabstatusid = cdcDictionaryEntity.getId();
						}
						labrep.setBusLabReportStatusId(buslabstatusid);
					}
					if (CommonUtil.isNotEmpty(reportdatestr)) {
						Date reportdate = sdf.parse(reportdatestr);
						labrep.setReportDate(reportdate);
					}
					if (CommonUtil.isNotEmpty(reportusername)) {
						labrep.setReportUserName(reportusername);
					}
					if (CommonUtil.isNotEmpty(checkdatestr)) {
						Date checkdate = sdf.parse(checkdatestr);
						labrep.setCheckDate(checkdate);
					}
					if (CommonUtil.isNotEmpty(checkusername)) {
						labrep.setCheckUserName(checkusername);
					}
	            	labrep.setDataId(dataId);
					labrep.setIsActive(1);
				} else {
					labrep.setIsActive(0);
				}
				// 先判断是不是有该对象
				Wrapper<CdcLabReportEntity> wrapper = new EntityWrapper<CdcLabReportEntity>();
				wrapper.eq("xcode", labrep.getXcode());
				wrapper.eq("data_id", dataId);
				int count = this.selectCount(wrapper);
				if (count > 0) {
					this.update(labrep, wrapper);
				} else {
					this.insert(labrep);
				}
				Element eleLabItems = labrepEle.element("labresults"); // 获取根节点
				// 检验结果
				Iterator<Element> iteritem = eleLabItems.elementIterator("labresult"); // 获取根节点下的子节点labresult
				while (iteritem.hasNext()) {
					Element labitemEle = iteritem.next();
					String xcodeitem = labitemEle.elementTextTrim("xcode"); // 索引码
					String labitemid = labitemEle.elementTextTrim("labitemid"); // 检验项目
					String result = labitemEle.elementTextTrim("result"); // 检测结果
					String resulttype = labitemEle.elementTextTrim("resulttype"); // 定性结果
					String resultnote = labitemEle.elementTextTrim("resultnote"); // 结果说明
					String abnormaldesc = labitemEle.elementTextTrim("abnormaldesc"); // 异常提示
					String resultunit = labitemEle.elementTextTrim("resultunit"); // 结果单位
					String resultrange = labitemEle.elementTextTrim("resultrange"); // 参考范围
					String resultmdr = labitemEle.elementTextTrim("resultmdr"); // 多耐结果
					// 保存检验结果
					CdcLabResultEntity labRst = new CdcLabResultEntity();
					labRst.setXcode(xcodeitem);
					if(CommonUtil.isNotEmpty(updatetimestr)) {
	            		Date updatetime = sdf.parse(updatetimestr);
	            		labRst.setUpdateDate(updatetime);
	            	}
	            	//获取更新人
	            	if(CommonUtil.isNotEmpty(updateuserid)) {
	            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
	            		cdcUserEntity.setXcode(updateuserid);
	            		cdcUserEntity.setDataId(basedataId);
	            		cdcUserEntity.setIsActive(1);
	            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
	            		//判断人员存在不存在
	            		Long updateuser = null;
	            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
	            			cdcUserEntity = new CdcUserEntity();
	            			cdcUserEntity.setXcode(updateuserid);
	                		cdcUserEntity.setIsActive(1);
	            			cdcUserEntity.setCode("newuser"+updateuserid);
	            			cdcUserEntity.setName("newuser"+updateuserid);
	                		cdcUserEntity.setDataId(basedataId);
	                		//保存用户
	                		cdcUserMapper.insert(cdcUserEntity);
	                		updateuser = cdcUserEntity.getId();
	            		}else {
	            			updateuser = cdcUserEntity.getId();
	            		}
	            		labRst.setUpdateBy(updateuser);
	            	}
					if ("1".equals(opercode)) {// 保存/修改
						// 获取labreportid
						Long labreportLongid = labrep.getId();
						labRst.setLabReportId(labreportLongid);
						// 获取labitemID
						if (CommonUtil.isNotEmpty(labitemid)) {
							CdcLabItemEntity cdcLabItemEntity = new CdcLabItemEntity();
							cdcLabItemEntity.setXcode(labitemid);
							cdcLabItemEntity.setDataId(dataId);
							cdcLabItemEntity.setIsActive(1);
							cdcLabItemEntity = cdcLabItemMapper.selectOne(cdcLabItemEntity);
							// 判断labitem存在不存在
							Long labitemlongid = null;
							if (CommonUtil.isNotEmpty(cdcLabItemEntity)) {// 存在
								labitemlongid = cdcLabItemEntity.getId();
								labRst.setLabItemId(labitemlongid);
							}
						}
						if (CommonUtil.isNotEmpty(result)) {
							labRst.setResult(result);
						}
						if (CommonUtil.isNotEmpty(resulttype)) {
							labRst.setResultType(resulttype);
						}
						if (CommonUtil.isNotEmpty(resultnote)) {
							labRst.setResultNote(resultnote);
						}
						if (CommonUtil.isNotEmpty(abnormaldesc)) {
							labRst.setAbnormalDesc(abnormaldesc);
						}
						if (CommonUtil.isNotEmpty(resultunit)) {
							labRst.setResultUnit(resultunit);
						}
						if (CommonUtil.isNotEmpty(resultrange)) {
							labRst.setResultRange(resultrange);
						}
						if (CommonUtil.isNotEmpty(resultmdr)) {
							labRst.setResultMdr(resultmdr);
						}
						labrep.setDataId(dataId);
						labRst.setIsActive(1);
					} else {
						labRst.setIsActive(0);
					}
					// 先判断是不是有该对象
					Wrapper<CdcLabResultEntity> itemwrapper = new EntityWrapper<CdcLabResultEntity>();
					itemwrapper.eq("xcode", labRst.getXcode());
					itemwrapper.eq("data_id", dataId);
					int itemcount = this.selectCount(wrapper);
					if (itemcount > 0) {
						cdcLabResultMapper.update(labRst, itemwrapper);
					} else {
						cdcLabResultMapper.insert(labRst);
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		} catch (Exception e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		}
		return "<response><status>1</status><message>ok</message></response>";
	}

}